app.controller("monitorCtrl", function ($scope, $interval, monitorService, systemConfigService, coreService, $log) {
    $log.info('MonitorController initialize');

    var CONFIG_BGS = "bgs";

    var CONFIG_DATABASE = "database";

    var CONFIG_MQ = "mq";

    var CONFIG_APP_UPLOAD = "appUpload";

    var CONFIG_AIR_INFO = "airInfo";

    var CONFIG_MSG_UP_CENTER = "msgUpCenter";

    var CONFIG_WEBSITE = "website";

    var CONFIG_FORWARDER = "forwarder";

    var CONFIG_IGNORE_ALARM = "ignoreAlarm";

    var CONFIG_ROLE_DISABLE = "roleDisable";

    var serverInfoAarr = [
        {typeId: 1, title: "AppUpload-舱单拆解服务", config: CONFIG_APP_UPLOAD},
        {typeId: 2, title: "MsgUpCenter-转报中心服务", config: CONFIG_MSG_UP_CENTER},
        {typeId: 3, title: "BGS服务", config: CONFIG_BGS},
        {typeId: 4, title: "舱单抓取程序", config: CONFIG_FORWARDER},
        {typeId: 5, title: "数据库", config: CONFIG_DATABASE},
        {typeId: 6, title: "本地MQ服务", config: CONFIG_MQ},
        {typeId: 7, title: "舱单数据", config: CONFIG_AIR_INFO},
        {typeId: 8, title: "地服网站", config: CONFIG_WEBSITE}
    ]

    /**
     * 页面初始化
     */
    $scope.init = function () {
        // 系统名称
        $scope.systemName = "机场地服监控系统";
        // 轮询时间
        $scope.interval = 5000;
        // 系统日志查询范围(24小时/3天/1周)-count:24,72,168
        $scope.count = 24;
        // 系统服务状态是否异常
        $scope.serverStatusError = false;

        // 展示监控状态
        $scope.showStatus();
        $interval($scope.showStatus, $scope.interval, -1);
        // 展示最新系统日志
        $scope.showLogs();
        $interval($scope.showLogs, $scope.interval, -1);

        // 获取告警日志
        $scope.getAlarmContents();
        $interval($scope.getAlarmContents, $scope.interval);

        $scope.initLine();

        $scope.initPie();

        // 获取忽略告警项
        $scope.getIgnor();
        $interval($scope.getIgnor, $scope.interval);

        // 监控机场地服的监控程序异常
        $scope.getServerDateTime();
        $interval($scope.getServerDateTime, 1000);
        // 数据绑定：节点信息
        $scope.serverInfoAarr = serverInfoAarr;
    };

    /**
     * 获取监控状态
     */
    $scope.showStatus = function () {
        // 参数
        var action = {
            action: 'showStatus'
        };
        monitorService.showStatus(action, function (data) {
            if (data.status === 'SUCCESS') {
                $log.info("show status success");
                $log.info(data.data.monitorServer);

                $scope.monitor = data.data.monitorServer;

                $scope.loadsheetData = data.data.monitorServer.msgUpCenter.loadsheetData;

                $scope.passgerlistData = data.data.monitorServer.msgUpCenter.passgerlistData;

                $scope.endTime = data.data.monitorServer.msgUpCenter.updateTime;

                $scope.timespan = data.data.monitorServer.msgUpCenter.timespan;

                $scope.points = data.data.monitorServer.msgUpCenter.points;

                $scope.total = data.data.monitorServer.msgUpCenter.totalCount;

                $scope.fail = data.data.monitorServer.msgUpCenter.failCount;

                $scope.success = $scope.total - $scope.fail;

                $scope.drawLine();

                $scope.drawPie();

            } else {
                $log.error("showStatus error:" + data.errorReason);
            }
        });
    };

    /**
     * 获取最新系统日志
     */
    $scope.showLogs = function () {
        // 参数
        var action = {
            action: 'showLogs',
            count: $scope.count
        };
        monitorService.showLogs(action, function (data) {
            if (data.status === 'SUCCESS') {
                $log.info("show logs success");
                $scope.serverLogs = data.data.logs;
            } else {
                $log.error("showLogs error:" + data.errorReason);
            }
        });
    };

    /**
     * 更改日志时间
     * @param count
     */
    $scope.changeLogCount = function (count) {
        $scope.count = count;
        $scope.showLogs();
    };

    /**
     * [2024-6-27：张丽娟：当机场地服的监控程序异常（只影响监控系统的功能，不影响舱单业务），
     * 则系统弹出如下告警提示：机场地服监控系统异常，请及时处理！]
     * 监控程序本身异常，系统不支持用户手动关闭弹出框和声音告警，需尽快恢复监控程序。
     * 监控程序恢复正常后，手动刷新界面重新进入系统，不再提示该告警]
     * 程序异常时，其他告警都不弹框，也不进行声音告警，只提示系统异常告警。
     *
     * 系统恢复后，需要刷新页面重新登录
     */
    $scope.getServerDateTime = function () {
        coreService.getServerDateTime({
            action: 'getServerDateTime'
        }, function (data) {
            $scope.serverStatusError = false;
        }, function (error) {
            $scope.serverStatusError = true;
            // 当监控系统异常时，关闭业务异常弹框
            $scope.closeAlarmModal();
        });
    };

    /**
     * 1：同时打开两个浏览器，一个浏览器确认告警后，另一个浏览器弹出框无法自动关闭
     *:2：当监控系统异常时，关闭业务异常弹框
     */
    $scope.closeAlarmModal = function () {
        // 主要解决，同时打开两个浏览器，一个浏览器确认告警后，另一个浏览器弹出框无法自动关闭
        // 当没有告警时，如果没有弹框，则不处理
        if ($('#alarmModal').data('bs.modal') === undefined) {
            return;
        }
        // 当没有告警时，如果弹框还未关闭，则关闭弹框
        if ($('#alarmModal').data('bs.modal').isShown) {
            $('#alarmModal').modal('hide');
        }
    }

    /**
     * 获取告警弹框内容
     */
    $scope.getAlarmContents = function () {
        // 当监控系统服务异常时，不再进行弹框和声音告警
        if ($scope.serverStatusError) {
            return;
        }
        // 参数
        var action = {
            action: 'getAlarmContents'
        };
        monitorService.getAlarmContents(action, function (data) {
            if (data.status === 'SUCCESS') {
                $log.info("getAlarmContents success");
                $scope.alarmContentList = data.data.alarmContentList;
                if ($scope.alarmContentList && $scope.alarmContentList.length > 0) {
                    // 当监控系统服务异常时，不再进行弹框和声音告警
                    if ($scope.serverStatusError) {
                        return;
                    }
                    // 获取第一条告警信息，进行弹框
                    $scope.firstAlarmContent = $scope.alarmContentList[0];
                    $('#alarmModal').modal('show');
                    // 读取告警声音
                    $scope.getVoiceContents();
                } else {
                    // 防止同时打开两个浏览器，一个浏览器确认告警后，另一个浏览器弹出框无法自动关闭
                    $scope.closeAlarmModal();
                }
            } else {
                $log.error("getAlarmContents error:" + data.errorReason);
            }
        });
    };

    /**
     * 告警确认
     */
    $scope.alarmConfirm = function (moduleName) {
        // 参数
        var action = {
            action: 'alarmConfirm',
            moduleName: moduleName
        };

        monitorService.alarmConfirm(action, function (data) {
            if (data.status === 'SUCCESS') {
                $log.info("alarmConfirm success");
                // 告警确认成功后，再关闭弹框
                $('#alarmModal').modal('hide');
                // 睡眠1秒再执行，等待模态框完全关闭（否则会出现，遮罩层叠加效果）
                setTimeout(function () {
                    $scope.getAlarmContents();
                    // 确保在AngularJS的digest cycle中运行
                    $scope.$apply();
                }, 1000);
            } else {
                $log.error("alarmConfirm error:" + data.errorReason);
            }
        });
    };

    /**
     * 获取声音告警内容
     * @param count
     */
    $scope.getVoiceContents = function () {
        // 判断当前是否有声音正在播放，本次播放完，再获取下一次告警
        if (window.speechSynthesis.speaking) {
            return;
        }
        if ($scope.alarmContentList && $scope.alarmContentList.length > 0) {
            $scope.startTextToSpeech($scope.alarmContentList)
        }
    };

    /**
     * 声音告警：声音告警播报内容格式如下：“机场地服监控系统XXX，请及时处理！（XXX为告警事件具体内容）”。
     * 如果有多个告警事件同时发生，则系统循环播报相应的告警内容，直至告警事件恢复或用户点击告警弹框的“确认”按钮。
     */
    $scope.startTextToSpeech = function (voiceContentList) {
        voiceContentList.forEach(function (content) {
            var voiceContent = $scope.systemName + content.moduleAlarmInfo + ',请及时处理!';
            $scope.readOutLoud(voiceContent);
        })
    };

    /**
     * 播放告警内容
     * @param count
     */
    $scope.readOutLoud = function (voiceContent) {
        // 空格为了解决第一次播报时，“飞机”读音不清晰,被吞吐掉了
        voiceContent = "  " + voiceContent.replace(/地/g, "帝");
        var msg = new SpeechSynthesisUtterance(voiceContent);
        msg.lang = 'zh-CN';
        window.speechSynthesis.speak(msg);
    };

    /**
     *[2024-6-25：杨家兴：增加服务重启功能]
     */
    $scope.restartAll = function (url, title) {
        // 弹出确认框
        message_confirm("提示", "是否重启" + title + "服务？", function (result) {
            if (result) {
                $.fn.jqLoading({height: 80, width: 240, text: "正在重启中，请耐心等待...."});
                // action
                var action = {
                    action: "restart",
                    moduleName: url
                };

                monitorService.restart(action, function (data) {
                    $.fn.jqLoading("destroy");
                    $scope.operateResult = data.data.reason;
                }, function () {
                    $.fn.jqLoading("destroy");
                });
            }
        });
    };
    /**
     * 加载弹窗所需数据
     * @param configType
     */
    $scope.clickMoreGetConfig = function (configType) {
        //加载配置信息
        $scope.showMoreConfig(configType);
    }

    /**
     * 获取操作框中的人员和解决方案信息
     * @param configType
     */
    $scope.showMoreConfig = function (configType) {
        $scope.showFlag = configType;
        // 参数
        var action = {
            action: "getSystemConfig",
            configType: configType
        };
        $.fn.jqLoading({height: 80, width: 240, text: "正在加载中，请耐心等待...."});
        systemConfigService.getSystemConfig(action, function (data) {
            $.fn.jqLoading("destroy");
            if (data.status === "SUCCESS") {
                if (!isNullOrEmpty(data.data.config)) {
                    $log.info(data.data.config);
                    $scope.targetDialog = data.data.config;
                    switch (configType) {
                        case CONFIG_BGS:
                            $scope.bgsConfig = data.data.config;
                            break;
                        case CONFIG_DATABASE:
                            $scope.databaseConfig = data.data.config;
                            break;
                        case CONFIG_MQ:
                            $scope.mqConfig = data.data.config;
                            break;
                        case CONFIG_APP_UPLOAD:
                            $scope.appUploadConfig = data.data.config;
                            break;
                        case CONFIG_AIR_INFO:
                            $scope.airInfoConfig = data.data.config;
                            msgAlarmList = data.data.config.msgAlarm;
                            break;
                        case CONFIG_MSG_UP_CENTER:
                            $scope.msgUpCenterConfig = data.data.config;
                            break;
                        case CONFIG_WEBSITE:
                            $scope.websiteConfig = data.data.config;
                            break;
                        case CONFIG_FORWARDER:
                            $scope.forwarderConfig = data.data.config;
                            break;
                        case CONFIG_IGNORE_ALARM:
                            $scope.ignoreAlarm = data.data.config;
                            break;
                        case CONFIG_ROLE_DISABLE:
                            $scope.roleDisable = data.data.config;
                            var checkbox = document.getElementById('subscribe');
                            checkbox.checked = $scope.roleDisable.roleDisable == "true" ? false : true
                            break;
                        default:
                            break;
                    }
                }
            } else {
                message_alert('提示', data.errorReason, null);
            }
        }, function () {
            $.fn.jqLoading("destroy");
        });

    };


    /**
     * 保存联系人和处理方法信息（弹窗里的数据）
     * @param configType
     */
    $scope.clickSaveremark = function () {
        // $('#exampleModal').modal('show')
        $scope.saveConfig($scope.showFlag, $scope.targetDialog);
    }


    /**
     * 保存系统配置
     * @param systemConfig
     */
    $scope.saveConfig = function (configType, configMap) {
        // 弹出确认框
        message_confirm("提示", "是否保存当前配置？", function (result) {
            if (result) {
                // action
                var action = {
                    action: "saveRemarkConfig",
                    configType: configType
                };

                systemConfigService.saveSystemConfig(action, configMap, function (data) {
                    if (data.status === 'SUCCESS') {
                        message_alert('提示', '保存成功', function () {
                            $scope.showMoreConfig(configType);
                            $scope.getIgnor();
                        });
                        $scope.operateResult = data.data.reason;
                    } else {
                        message_alert('提示', '保存失败', null);
                        $scope.operateResult = data.data.reason;
                    }
                });
            }
        });

    };

    /**
     * [2024-6-25：杨家兴：系统支持对指定告警项进行声音和弹窗告警忽略的功能]
     * @param configType
     */
    $scope.getIgnor = function () {
        // 参数
        var action = {
            action: "getSystemConfig",
            configType: "ignoreAlarm"
        };
        systemConfigService.getSystemConfig(action, function (data) {
            if (data.status === "SUCCESS") {
                if (!isNullOrEmpty(data.data.config)) {
                    $scope.ignoreAlarmDisplay = data.data.config.ignore.map(obj => obj.id);
                }
            } else {
                message_alert('提示', data.errorReason, null);
            }
        }, function () {
        });

    };


    /**
     * 初始化折线图
     */
    $scope.initLine = function () {
        //传参
        $scope.loadsheetData = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

        $scope.passgerlistData = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];


        // X轴坐标时间刻度集合
        $scope.timeArray = [];

        // X轴结束时间
        $scope.endTime = new Date().getTime();
        // X轴时间刻度间隔
        $scope.timespan = 5;
        // X轴时间刻度个数
        $scope.points = 12;

        $scope.line = echarts.init(document.getElementById('line'));

        // 画折线图
        $scope.drawLine();
    };

    /**
     * 初始化饼图
     */
    $scope.initPie = function () {
        //传参
        $scope.total = 0;
        $scope.success = 0;
        $scope.fail = 0;

        $scope.pie = echarts.init(document.getElementById('pie'));

        // 画饼状图
        $scope.drawPie();
    };


    /**
     * 计算x轴的时间坐标刻度
     * @param endTime
     * @param timespan
     * @param points
     */
    $scope.calculationX = function (endTime, timespan, points) {
        $scope.timeArray = [];
        var startTime = endTime - timespan * points * 60 * 1000;
        for (var i = 1; i <= points; i++) {
            var modTine = new Date(startTime + (timespan * 60 * 1000) * i);
            $scope.timeArray.push(modTine.toJSON().replace(/[-T]/g, '').substr(8, 5));
        }
    };

    /**
     * 画折线图
     */
    $scope.drawLine = function () {
        // 计算X轴坐标时间刻度集合
        $scope.calculationX($scope.endTime, $scope.timespan, $scope.points);


        // 指定图表的配置项和数据
        var option = {
            title: {
                show: true,
                text: '上行报变化曲线',
                left: 'center',
                textStyle: {
                    fontSize: 18,
                    fontWeight: 'bolder',
                    color: '#FAFAFA'
                }
            },
            color: ['#FF3B30', '#A5E8F0'],
            legend: {
                orient: 'horizontal',
                left: 'left',
                textStyle: {
                    color: '#FFFFFF'
                },
                data: ['名单', '舱单']
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a}:{c}'
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                nameTextStyle: {
                    color: '#337ab7'
                },
                axisLabel: {
                    color: '#337ab7'
                },
                axisLine: {
                    lineStyle: {color: '#337ab7'}  //x轴坐标轴颜色
                },
                axisTick: {
                    lineStyle: {color: '#337ab7'},  //x轴坐标刻度颜色
                    interval: 0
                },
                data: $scope.timeArray
            },
            yAxis: [
                {
                    name: '舱单',
                    splitLine: {
                        show: false
                    },
                    nameTextStyle: {
                        color: '#337ab7'
                    },
                    axisLabel: {
                        color: '#337ab7'
                    },
                    axisLine: {
                        lineStyle: {color: '#337ab7'}  //y轴坐标轴颜色
                    },
                    axisTick: {
                        lineStyle: {color: '#337ab7'}  //y轴坐标刻度颜色
                    },
                    type: 'value'
                },
                {
                    name: '名单',
                    splitLine: {
                        show: false
                    },
                    nameTextStyle: {
                        color: '#337ab7'
                    },
                    axisLabel: {
                        color: '#337ab7'
                    },
                    axisLine: {
                        lineStyle: {color: '#337ab7'}  //y轴坐标轴颜色
                    },
                    axisTick: {
                        lineStyle: {color: '#337ab7'}  //y轴坐标刻度颜色
                    },
                    type: 'value'
                }
            ],
            series: [
                {
                    name: '名单',
                    type: 'line',
                    yAxisIndex: 1,
                    data: $scope.passgerlistData
                },
                {
                    name: '舱单',
                    type: 'line',
                    data: $scope.loadsheetData
                }
            ]
        };

        // 使用刚指定的配置项和数据显示图表。
        $scope.line.setOption(option);
    };

    /**
     * 画饼状图
     */
    $scope.drawPie = function () {

        // 指定图表的配置项和数据
        var option = {
            title: {
                show: true,
                text: '报文发送成功率',
                left: 'center',
                textStyle: {
                    fontSize: 18,
                    fontWeight: 'bolder',
                    color: '#FAFAFA'
                }
            },

            color: ['#E76A6A', '#8DD6E9'],
            tooltip: {
                trigger: 'item',
                formatter: '{b} : {d}% ({c})'
            },
            series: [
                {
                    name: '',
                    type: 'pie',
                    radius: '55%',
                    center: ['50%', '60%'],
                    label: {
                        position: 'auto',
                        normal: {
                            show: true,
                            interval: 'auto',
                            rotate: 0,
                            formatter: '{b} : {d}%'
                        }
                    },
                    data: [
                        {value: $scope.fail, name: '失败率'},
                        {value: $scope.success, name: '成功率'}
                    ],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };

        // 使用刚指定的配置项和数据显示图表。
        $scope.pie.setOption(option);
    }

});
// 全局变量 angular的$scope作用域
var $scope = null;

// 加载完页面后，给$scope赋值
window.onload = function () {
    //获取ng-controller元素
    var element = document.querySelector('[ng-controller=monitorCtrl]');
    //获取$scope变量
    $scope = angular.element(element).scope();
    $('#exampleModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget) // Button that triggered the modal
        var recipient = button.data('whatever') // Extract info from data-* attributes
        // 使用 find() 方法查找数组中对应的对象
        var item = $scope.serverInfoAarr.find(function (el) {
            return el.typeId === recipient;
        });
        $scope.operateResult = "";
        var modal = $(this)
        modal.find('.modal-title').text(item.title + "操作")
        $scope.clickMoreGetConfig(item.config)
    })
};


